<template>
	<view>
		<uni-popup ref="dateselect" @maskClick="closePopup()">
			<view class="popup-bd">
				<view class="popup-title mt20">
					时间选择
					<uni-icons
						type="closeempty"
						size="50rpx"
						color="#666666"
						class="popup-close"
						@click="closePopup()"
					></uni-icons>
				</view>
				<view class="popup-content">
					<view class="tab-line1" v-if="!halfTrue">
						<scroll-view
							scroll-x="true"
							:scroll-into-view="scrollIndex"
							scroll-with-animation="true"
							class="tab-bar1"
						>
							<view
								class="tab-item1"
								:class="
									item.value === activeDay ? 'tab-active' : ''
								"
								v-for="item in dataList"
								:key="item.value"
								:id="'scroll' + item.value"
								@click="changeDay(item.value)"
							>
								<view>{{ item.week }}</view>
								<view class="mb20">{{ item.day }}</view>
								<hr
									:class="
										item.value == activeDay
											? 'tab-active-line'
											: ''
									"
								/>
							</view>
						</scroll-view>
					</view>
					<!-- 时间段 -->
					<view class="box-bd-cont mt20 df fx-wp">
						<view
							class="item-box"
							v-for="(timeItem, timeIndex) in timeList"
							:key="timeIndex"
						>
							<view
								:class="{
									'time-active': timeItem === timeActive,
									'time-disabled': getTimeDisabled(timeItem),
								}"
								class="item-cont"
								@tap="changeTime(timeItem, timeIndex)"
							>
								{{ timeItem }}
							</view>
						</view>
					</view>
				</view>
				<view class="popup-bottom df ac"
					><button
						class="primary-button w90"
						@tap="submitChooseDate()"
					>
						确定
					</button></view
				>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { getCurrentDay } from '@/common/utils.js'
import { nextTick } from 'vue'
const dayjs = require('@/common/dayjs.min.js')
export default {
	name: 'diy-dateselect',
	props: {
		show: {
			type: Boolean,
			value: false,
			default: false,
		},
		value: {
			type: Array,
			value: [],
			default() {
				return []
			},
		},
		halfTrue: {
			type: Boolean,
			value: false,
			default: false,
		},
		//最小日期限制
		minDate: {
			type: [Array, String],
			default: '',
		},
		//最大日期限制
		maxDate: {
			type: [Array, String],
			default: '',
		},
		orderData: {
			type: Object,
			default: () => {
				return {}
			},
		},
		//选择结束时间传入开始时间，用以计算是否需要
		finishDateBefor: {
			type: Number,
			default: 0,
		},
	},
	data() {
		return {
			dayjs,
			dataList: [],
			activeDay:
				this.value[0] ||
				`${new Date().getFullYear()}-${
					(new Date().getMonth() + 1).toString().length === 1
						? '0' + (new Date().getMonth() + 1)
						: new Date().getMonth() + 1
				}-${
					new Date().getDate().toString().length == 1
						? '0' + new Date().getDate()
						: new Date().getDate()
				}`,
			timeList: [],
			timeActive: '',
			current: '',
			nowTimeIndex: 0,
			nowDay: '',
			minDateInt: 0,
			maxDateInt: 0,
			nowDateInt: 0,
			scrollIndex: '',
			timeBefore: 1,
			timeParticle: 1,
		}
	},
	methods: {
		getTimeDisabled(timeValue) {
			const { minDateInt, maxDateInt, activeDay, minDate, maxDate } = this
			const activeDayInt = parseInt(activeDay.replace(/-/g, ''))
			const dayLimit =
				(minDateInt && activeDayInt < minDateInt) ||
				(maxDateInt && activeDayInt > maxDateInt)
			if (dayLimit) {
				return dayLimit
			} else {
				const timeValueInt = parseInt(timeValue.replace(':', ''))
				// 判断是否在 最大&最小之间的时间段
				if (
					minDateInt === activeDayInt ||
					maxDateInt === activeDayInt
				) {
					// 不包含最小值
					return (
						(Array.isArray(minDate) &&
							timeValueInt <=
								parseInt(minDate[1].replace(':', ''))) ||
						(Array.isArray(maxDate) &&
							timeValueInt <
								parseInt(maxDate[1].replace(':', '')))
					)
				} else {
					return false
				}
			}
		},
		changeDay(val) {
			this.activeDay = val
			this.scrollIndex = 'scroll' + val
		},
		changeTime(timeVal, timeIndex) {
			const data = `${new Date().getFullYear()}-${
				(new Date().getMonth() + 1).toString().length === 1
					? '0' + (new Date().getMonth() + 1)
					: new Date().getMonth() + 1
			}-${
				new Date().getDate().toString().length == 1
					? '0' + new Date().getDate()
					: new Date().getDate()
			}`
			this.nowDateInt = parseInt(this.activeDay.replace(/-/g, ''))
			if (
				(!this.minDateInt && !this.maxDateInt) ||
				(this.minDateInt &&
					!this.maxDateInt &&
					this.nowDateInt >= this.minDateInt) ||
				(!this.maxDateInt &&
					this.minDateInt &&
					this.nowDateInt <= this.maxDateInt) ||
				(this.minDateInt &&
					this.maxDateInt &&
					this.nowDateInt >= this.minDateInt &&
					this.nowDateInt <= this.maxDateInt)
			) {
				this.timeActive = timeVal
			}
		},
		getTimeSlot() {
			let arr = []
			this.timeList = []
			for (let i = 0; i < 24; i++) {
				let one = i > 9 ? `${i}:00` : `${'0' + i}:00`
				if (!this.halfTrue && this.timeParticle === 2) {
					let two = i > 9 ? `${i}:30` : `${'0' + i}:30`
					let total = [one, two]
					arr.push(...total)
				} else {
					let total = [one]
					arr.push(...total)
				}
			}
			this.timeList = arr
		},
		getDate(month, val) {
			let dayVal = ''
			if (
				month == new Date().getMonth() + 1 &&
				val == new Date().getDate()
			) {
				dayVal = '今天'
			} else if (
				month == new Date().getMonth() + 1 &&
				val == new Date().getDate() + 1
			) {
				dayVal = '明天'
			}
			return dayVal
		},
		//根据月份获取天数和对应的星期
		monthDays() {
			let _that = this
			let nowDate = new Date()
			let startDate = new Date()
			let endDate = new Date()
			let beforTime = 1
			if (this.orderData.serviceType === 5) {
				beforTime = 183
			} else if (this.finishDateBefor) {
				beforTime = this.finishDateBefor
			} else {
				beforTime = this.timeBefore ? this.timeBefore : 1
			}
			startDate.setDate(nowDate.getDate() - parseInt(beforTime))
			endDate.setMonth(nowDate.getMonth() + 6)
			let dataList = []
			// 创建周数据
			let weeks = ['日', '一', '二', '三', '四', '五', '六']
			while (endDate.getTime() - startDate.getTime() >= 0) {
				let year = startDate.getFullYear()
				let month =
					(startDate.getMonth() + 1).toString().length === 1
						? '0' + (startDate.getMonth() + 1)
						: startDate.getMonth() + 1
				let day =
					startDate.getDate().toString().length == 1
						? '0' + startDate.getDate()
						: startDate.getDate()
				let week = weeks[startDate.getDay()]

				dataList.push({
					day: `${month}月${day}日`,
					week:
						_that.getDate(month, startDate.getDate()) ||
						`星期${week}`,
					value: `${year}-${month}-${day}`,
				})
				startDate.setDate(startDate.getDate() + 1)
			}
			this.dataList = dataList
		},
		closePopup() {
			this.$emit('close')
		},
		submitChooseDate() {
			let chooseDay = ''
			this.nowDateInt = parseInt(this.activeDay.replace(/-/g, ''))
			if (
				(!this.minDateInt && !this.maxDateInt) ||
				(this.minDateInt &&
					!this.maxDateInt &&
					this.nowDateInt >= this.minDateInt) ||
				(!this.minDateInt &&
					this.maxDateInt &&
					this.nowDateInt <= this.maxDateInt) ||
				(this.minDateInt &&
					this.maxDateInt &&
					this.nowDateInt >= this.minDateInt &&
					this.nowDateInt <= this.maxDateInt)
			) {
				chooseDay = this.activeDay
			} else {
				chooseDay = this.value[0] || this.nowDay
			}
			const data = this.halfTrue
				? this.timeActive
				: [chooseDay, this.timeActive]
			this.$emit('submit', data)
			this.$emit('close')
		},
		//获取并返回当天日期
		getNowDay() {
			return `${new Date().getFullYear()}-${
				(new Date().getMonth() + 1).toString().length === 1
					? '0' + (new Date().getMonth() + 1)
					: new Date().getMonth() + 1
			}-${
				new Date().getDate().toString().length == 1
					? '0' + new Date().getDate()
					: new Date().getDate()
			}`
		},
		//订单配置
		getOrderConfig(func) {
			let _that = this
			this.$request
				.request('carer-platform/orderConfig/getOrderConfig', {
					data: {
						orgId: this.orderData.orgId,
						hospitalId: this.orderData.hospitalId,
					},
				})
				.then((res) => {
					if (res.success) {
						let orderConfig = res.data || {}
						_that.timeBefore =
							orderConfig.timeBefore || 0
								? orderConfig.timeBefore
								: 1
						_that.timeParticle =
							orderConfig.timeParticle || 0
								? orderConfig.timeParticle
								: 1
						func && func()
					}
				})
		},
		//初始化数据
		initData() {
			this.monthDays()
			this.getTimeSlot()
			const minutes = new Date().getMinutes()
			const hours = new Date().getHours()
			let current = ''
			let newHour = parseInt(hours) + 1
			newHour = newHour > 9 ? newHour : '0' + newHour
			current = `${newHour}:00`
			// if (minutes <= 59) {

			// } else {
			// 	current = `${hours}:00`
			// }
			this.current = current
			this.timeActive = this.value[1] || current
			this.nowTimeIndex = 0
			this.timeList.forEach((item, index) => {
				if (item === this.timeActive) {
					this.nowTimeIndex = index
				}
			})
			this.nowDay = this.getNowDay()
			this.activeDay = this.value[0] || this.nowDay
			this.minDateInt = this.getDateInt(this.minDate)
			this.maxDateInt = this.getDateInt(this.maxDate)
			this.nowDateInt = this.activeDay
				? parseInt(this.activeDay.replace(/-/g, ''))
				: ''
			this.$nextTick(() => {
				this.scrollIndex = 'scroll' + this.activeDay
			})
		},
		getDateInt(date) {
			if (Array.isArray(date)) {
				return date.length ? parseInt(date[0].replace(/-/g, '')) : ''
			} else {
				return date ? parseInt(date.replace(/-/g, '')) : ''
			}
		},
	},
	watch: {
		show(val) {
			let _that = this
			if (val) {
				this.scrollIndex = ''
				if (this.orderData.hospitalId && this.orderData.orgId) {
					this.getOrderConfig(() => {
						_that.initData()
					})
				} else {
					_that.initData()
				}

				this.$refs.dateselect.open('bottom')
			} else {
				this.$refs.dateselect.close()
			}
		},
		activeDay(newVal) {
			const data = `${new Date().getFullYear()}-${
				(new Date().getMonth() + 1).toString().length === 1
					? '0' + (new Date().getMonth() + 1)
					: new Date().getMonth() + 1
			}-${
				new Date().getDate().toString().length == 1
					? '0' + new Date().getDate()
					: new Date().getDate()
			}`
			if (newVal === data) {
				this.timeActive = this.value[1] || this.current
			}
		},
	},
}
</script>

<style scoped lang="scss">
.tab-line1 {
	height: 130rpx;
	line-height: 130rpx;
	overflow: hidden;
	width: 100%;
}
.tab-bar1 {
	width: 100%;
	box-sizing: content-box;
	height: 130rpx;
	position: relative;
	background-color: #ffffff;
	overflow-x: auto;
	overflow-y: hidden;
	-webkit-overflow-scrolling: touch;
	user-select: none;
	padding-bottom: 30rpx;
	white-space: nowrap;
}
.tab-item1 {
	display: inline-block;
	line-height: 50rpx;
	position: relative;
	text-align: center;
	font-size: 36rpx;
	color: #6b686b;
	position: relative;
	align-items: center;
	justify-content: center;
	padding: 0 20rpx;
}
.tab-active {
	color: $primary-color;
}
.item-box {
	width: 25%;
	height: 110rpx;
}
.item-cont {
	height: 50rpx;
	font-size: 38rpx;
	border: 2rpx solid #eeeeee;
	padding: 20rpx 0;
	text-align: center;
	margin: 4rpx;
}
.box-bd-cont {
	background-color: #ffffff;
	width: 100%;
	height: calc(100vh - 520rpx);
	overflow-y: auto;
	align-content: flex-start;
}
.time-active {
	background: $primary-color;
	color: #fff;
}
.time-disabled {
	background-color: #fafafa;
	color: #999999;
}
.tab-active-line {
	width: 80%;
	min-height: 5rpx;
	background-color: $primary-color;
	color: $primary-color;
}
.tab-active {
	font-weight: 900;
}
</style>
